﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Forms;
using CompatCheckAndMigrate.Helpers;
using CompatCheckAndMigrate.ObjectModel;

namespace CompatCheckAndMigrate.Controls
{
    public partial class RemoteServerControl : UserControl, IWizardStep
    {
        private BackgroundWorker _worker;
        public RemoteServerControl()
        {
            InitializeComponent();
        }

        public event EventHandler<GoToWizardStepEventArgs> GoTo;

        public void SetState(object state, bool isNavigatingBack = false)
        {
            if (!isNavigatingBack) {
                MainForm.WriteTrace("in set state remote");
                busyMessageLabel.Visible = busyPictureBox.Visible = false;
                cbxDrive.SelectedIndex = 0;
                // select local by default
                radioLocal.Select();
                radioLocal.Checked = true;
                tbxComputerName.Enabled =
                    tbxPassword.Enabled = tbxUsername.Enabled = cbxDrive.Enabled = radioRemote.Checked = false;
            }
        }

        private void FireGoToEvent(WizardSteps step, object state = null)
        {
            EventHandler<GoToWizardStepEventArgs> _goTo = GoTo;
            if (_goTo != null)
            {
                _goTo(this, new GoToWizardStepEventArgs(step, state));
            }
        }

        private void RemoteServerControl_Load(object sender, EventArgs e)
        {
            busyMessageLabel.Visible = busyPictureBox.Visible = false;
            cbxDrive.SelectedIndex = 0;
            // select local by default
            radioLocal.Select();
            radioLocal.Checked = true;
            tbxComputerName.Enabled =
                tbxPassword.Enabled = tbxUsername.Enabled = cbxDrive.Enabled = radioRemote.Checked = false;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (radioRemote.Checked)
            {
                string computername = tbxComputerName.Text;
                string username = tbxUsername.Text;
                string password = tbxPassword.Text;
                string driveLetter = cbxDrive.Text;

                busyMessageLabel.Text = "Trying to connect to " + computername;
                busyMessageLabel.Visible = busyPictureBox.Visible = true;
                tbxComputerName.Enabled = tbxUsername.Enabled = tbxPassword.Enabled = cbxDrive.Enabled = radioRemote.Enabled = radioLocal.Enabled = false;
                _worker = new BackgroundWorker();
                bool connectionSuccessful = false;
                btnConnect.Enabled = false;

                _worker.DoWork += (object doWorkSender, DoWorkEventArgs doWorkEventArgs) =>
                {
                    if (!string.IsNullOrEmpty(computername) && Helper.IsComputerReachable(computername))
                    {
                        if (Helper.ConnectToServer(computername, username, password))
                        {
                            RemoteSystemInfo.Initialize(computername, username, password, driveLetter);
                            connectionSuccessful = true;
                        }
                    }
                };

                _worker.RunWorkerCompleted += (object runWorkerCompletedSender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs) =>
                {
                    // Hide busy animation.
                    this.busyPictureBox.Visible = this.busyMessageLabel.Visible = false;
                    tbxComputerName.Enabled = tbxUsername.Enabled = tbxPassword.Enabled = cbxDrive.Enabled = radioRemote.Enabled = radioLocal.Enabled = true;
                    btnConnect.Enabled = true;
                    if (runWorkerCompletedEventArgs.Error != null || !connectionSuccessful)
                    {
                        string message = runWorkerCompletedEventArgs.Error != null ? runWorkerCompletedEventArgs.Error.Message : "Could not connect to the computer specified with the credentials supplied";
                        MessageBox.Show(message,
                            System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        var remoteSystemInfo = RemoteSystemInfo.GetRemoteSystemInfo;
                        if (remoteSystemInfo.IISVersion >= 7 && Helper.IisVersion < 7)
                        {
                            MessageBox.Show(
                                "To migrate sites on a web server 7 and higher, run the tool from a system running Vista or above. ",
                                System.Windows.Forms.Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        else
                        {
                            FireGoToEvent(WizardSteps.MigrationCandidates, remoteSystemInfo);
                        }
                    }
                };

                _worker.RunWorkerAsync();
            }
            else
            {
                FireGoToEvent(WizardSteps.MigrationCandidates, null);
            }
        }

        private void radioRemote_CheckedChanged(object sender, EventArgs e)
        {
            tbxComputerName.Enabled = tbxPassword.Enabled = tbxUsername.Enabled = cbxDrive.Enabled = radioRemote.Checked;
        }

        private void tbxComputerName_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnConnect.PerformClick();
            }
        }

        private void tbxUsername_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnConnect.PerformClick();
            }
        }

        private void tbxPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnConnect.PerformClick();
            }
        }

        private void cbxDrive_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnConnect.PerformClick();
            }
        }

        private void radioLocal_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnConnect.PerformClick();
            }
        }
    }
}
